package com.xinnet.mms.quartz.job;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.core.utils.INetUtils;
import com.xinnet.mms.allot.dao.CustomAllotDao;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.CustomerCare;
import com.xinnet.mms.member.service.MemberService;
import com.xinnet.mms.order.service.OrderService;
import com.xinnet.mms.utils.CustomerManage;

@Service(value = "rebateCustomAllotJob")
/**
 * 针对通过返利注册的会员进行定时分配
 * @author 王志军
 * @since 2015-10-03
 */
public class RebateCustomAllotJob {

	/** 客户分配 */
	@Autowired
	private CustomAllotDao customAllotDao;
	private static final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/** 时间戳 */
	@Autowired
	private JobTimeService jobTimeService;
	@Autowired
	private CustomAllotService customAllotService;
	/** 会员中心 */
	@Autowired
	private MemberService memberService;
	/**xinne库--订单*/
	@Autowired
	private  OrderService orderService;
	
	private static Log log = LogFactory.getLog(RebateCustomAllotJob.class);
	/**
	 * 查询分配状态为 未分配保留（2）的客户列表
	 * 会员24小时内未购买商品，超出24小时系统自动按分配规则分配；如会员在24小时内通过返利购买了商品，待会员超出（60天）后系统自动按分配规则进行分配。
	 */
	@Transactional(propagation=Propagation.REQUIRES_NEW,readOnly=false)
	public void scanRetainAllot(){
		// 指定特定服务器IP来跑定时任务
		String ip = INetUtils.getLocalHostAddress();
		log.info("<当前IP：(" + ip + ")>");
		try {
			Customer jobTimeCustomer = null;
			jobTimeCustomer = jobTimeService.getJobTime(CustomerManage.QUERYRETAIN);
			if(jobTimeCustomer==null){
				jobTimeCustomer = new Customer();
				String time = sf.format(new Date());
				jobTimeCustomer.setTimeStamp(time);
				jobTimeCustomer.setJobId(UUID.randomUUID().toString());
				jobTimeCustomer.setJobType(CustomerManage.QUERYRETAIN);
				jobTimeService.addJobTime(jobTimeCustomer);
			}
			
			String resultTime = jobTimeCustomer.getTimeStamp();
			List<Customer> customerList = customAllotService.getRebateCustomer(CustomerManage.ALLOT_NO_RETAIN, resultTime);
			String isTest = ConfigUtil.getString("isTest");
	        if(isTest==null || "".equals(isTest)){
	        	log.error("配置异常：是否是测试环境");
	        	return;
	        }
			if(customerList!=null){
				for (Customer customer : customerList) {
					jobTimeCustomer.setTimeStamp(customer.getAddTime());
					String addTimeStr = customer.getAddTime();
					Date addTime = sf.parse(addTimeStr);
					Calendar cal = Calendar.getInstance();
					cal.setTime(addTime);
					if(isTest.equals("true")){
						cal.add(Calendar.MINUTE, 24);
					} else {
						cal.add(Calendar.HOUR, 24);
					}
					Date nowDate = new Date();
					//当前时间小于会员创建时间
					if(nowDate.after(cal.getTime())){
						//判断会员是否有购买商品
						List<CustomerCare> orderList=orderService.getOrdersByCusId(customer.getCusId());
						if(orderList != null && orderList.size() != 0){
							//购买过商品
							customer.setCustomerSource("网站");
							customer.setCustomState(CustomerManage.ACCEPT_NO);
							customer.setPusherId("system");
							customer.setIsAllot(CustomerManage.ALLOT_NO_REBATE);
							customer.setIsReDevel(0);
							customer.setCustomerType(CustomerManage.NEW_CUSTOMER);
							//customAllotService.addNewCustomer(customer);
							customAllotService.updateCustomerIsAllot(customer);
						} else {
							// 未购买过商品,按默认规则进行分配
							try {
								customer.setCustomerSource("网站");
								customer.setCustomState(CustomerManage.ACCEPT_NO);
								customer.setPusherId("system");
								customer.setIsAllot(0);
								customer.setIsReDevel(0);
								customer.setCustomerType(CustomerManage.NEW_CUSTOMER);
								customAllotService.updateCustomerIsAllot(customer);
								customAllotService.allot(customer, CustomerManage.NEW_CUSTOMER);
							} catch (Exception e) {
								jobTimeService.updateJobTime(jobTimeCustomer);
								log.error("<按默认规则分配会员出错-会员ID:" + customer.getCusId()
										+ "," + e.getMessage() + ">", e);
							}
						}
					}
					
				}
				jobTimeService.updateJobTime(jobTimeCustomer);
			} else {
					log.info("查找的返利会员任务为空："+new Date());
			}
			
		} catch (Exception e) {
			log.error("同步会员出错：" + e.getMessage(),e);
		}
		
	}
	
	@Transactional(propagation=Propagation.REQUIRES_NEW,readOnly=false)
	public void scanRebateAllot(){
		// 指定特定服务器IP来跑定时任务
		String ip = INetUtils.getLocalHostAddress();
		log.info("<当前IP：(" + ip + ")>");
		Customer jobTimeCustomer = null;
		try {
			jobTimeCustomer = jobTimeService.getJobTime(CustomerManage.QUERYREBATE);
			if(jobTimeCustomer==null){
				jobTimeCustomer = new Customer();
				String time = sf.format(new Date());
				jobTimeCustomer.setTimeStamp(time);
				jobTimeCustomer.setJobId(UUID.randomUUID().toString());
				jobTimeCustomer.setJobType(CustomerManage.QUERYREBATE);
				jobTimeService.addJobTime(jobTimeCustomer);
			}
			
			String resultTime = jobTimeCustomer.getTimeStamp();
			List<Customer> customerList = customAllotService.getRebateCustomer(CustomerManage.ALLOT_NO_RETAIN, resultTime);
			String isTest = ConfigUtil.getString("isTest");
	        if(isTest==null || "".equals(isTest)){
	        	log.error("配置异常：是否是测试环境");
	        	return;
	        }
			if(customerList!=null){
				for (Customer customer : customerList) {
					jobTimeCustomer.setTimeStamp(customer.getAddTime());
					String addTimeStr = customer.getAddTime();
					Date addTime = sf.parse(addTimeStr);
					Calendar cal = Calendar.getInstance();
					cal.setTime(addTime);
					if(isTest.equals("true")){
						cal.add(Calendar.MINUTE, 60);
					} else {
						cal.add(Calendar.HOUR, 60);
					}
					Date nowDate = new Date();
					//当前时间小于会员创建时间
					if(nowDate.after(cal.getTime())){
						customer.setCustomerSource("网站");
						customer.setCustomState(CustomerManage.ACCEPT_NO);
						customer.setPusherId("system");
						customer.setIsAllot(0);
						customer.setIsReDevel(0);
						customer.setCustomerType(CustomerManage.NEW_CUSTOMER);
						customAllotService.updateCustomerIsAllot(customer);
						try {
							customAllotService.allot(customer, CustomerManage.NEW_CUSTOMER);
						} catch (Exception e) {
							jobTimeService.updateJobTime(jobTimeCustomer);
							log.error("<按默认规则分配会员出错-会员ID:" + customer.getCusId()
									+ "," + e.getMessage() + ">", e);
						}
					}
				}
				jobTimeService.updateJobTime(jobTimeCustomer);
			} else {
				log.info("查找的返利会员任务为空"+new Date());
			}
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	public CustomAllotDao getCustomAllotDao() {
		return customAllotDao;
	}
	public void setCustomAllotDao(CustomAllotDao customAllotDao) {
		this.customAllotDao = customAllotDao;
	}
	public JobTimeService getJobTimeService() {
		return jobTimeService;
	}
	public void setJobTimeService(JobTimeService jobTimeService) {
		this.jobTimeService = jobTimeService;
	}
	public CustomAllotService getCustomAllotService() {
		return customAllotService;
	}
	public void setCustomAllotService(CustomAllotService customAllotService) {
		this.customAllotService = customAllotService;
	}
	public OrderService getOrderService() {
		return orderService;
	}
	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
}
